
#include "stdafx.h"

#include "Database.h"
#include "SpriteMap.h"
#include "ScreenManager.h"
#include "BattleManager.h"

bool BattlerZComp(const DisplayObject* a, const DisplayObject* b) {
	if (a == NULL || b == NULL) return false;
	const Sprite* sa = dynamic_cast<const Sprite*>(a);
	const Sprite* sb = dynamic_cast<const Sprite*>(b);
	const SpriteBattler* aa = dynamic_cast<const SpriteBattler*>(sa);
	const SpriteBattler* bb = dynamic_cast<const SpriteBattler*>(sb);
	int ay, by, az, bz;
	ay = (aa == NULL ? sa->y+sa->getSpriteHeight() : aa->getBattlerY());
	az = (aa == NULL ? sa->z : aa->getBattlerZ());
	by = (bb == NULL ? sb->y+sb->getSpriteHeight() : bb->getBattlerY());
	bz = (bb == NULL ? sb->z : bb->getBattlerZ());
	return (ay == by) ? az < bz : ay < by;
}
//
SpriteMap::SpriteMap(BattleField* battleField): Sprite(battleField->fileName){
	this->battleField = battleField;
	actor = BattleManager::getActor();
}
void SpriteMap::addBattler(SpriteBattler* battler) {
	battlers.push_back(battler);
	addChild(battler);
}
void SpriteMap::removeBattler(SpriteBattler* battler) {
	vector<SpriteBattler*>::iterator pos;
	pos = find(battlers.begin(), battlers.end(), battler);
	if (pos != battlers.end()) battlers.erase(pos);
	removeChild(battler);
}

void SpriteMap::updateOthers() {
	Sprite::updateOthers();
	updateBattlers();
	updateScroll();
}
void SpriteMap::updateBattlers() {
	for (int i = 0; i < battlers.size(); i++) {
		if (battlers[i]->isMoved()) {
			sort(children.begin(), children.end(), BattlerZComp);
			break;
		}
	}
}
void SpriteMap::updateScroll() {
	int ax = actor->getX(), ay = actor->getY();
	int ox = ax - SWidth / 2, oy = ay - SHeight*3 / 4;
	ox = -max(0, min(ox, width - SWidth));
	oy = -max(0, min(oy, height - SHeight));
	x += (ox - x) / 4;
	y += (oy - y) / 4;
}